IPython maintains a history of all the commands you type. It even maintains this across sessions.
You should work through the commands in this Notebook in an ordinary IPython session since this notebook wan't have any history.
Just history
will show you your history.
history [range [range] ...]
shows the history in the specified range(s). Here's the note on ranges from the history help.
4
4-6
243/1-5
~2/7
~8/1-~6/5
Multiple ranges can be entered, separated by spaces
history -n
will show you the index number of each command.
history -l <number>
shows the last <number>
commands.
history -g [pattern [pattern] ...]
treats the argument pattern(s) as a glob to search back through
your complete history. The pattern may contain ?
to match one unknown character and *
to match
any number of unknown characters. Use '%hist -g'to show full saved history (may be very long).
history -u -g [pattern [pattern] ...]
is the same as above but the -u shows only unique commands.
There is also a set of variables that allow you to access previous commands. _i
is the
previous command and _i2
is the one before, all the way up to _i9
.
Let's enter some commands and see how it works.
In [1]:
2 + 2
Out[1]:
In [2]:
"A string" " connected to another string"
Out[2]:
In [3]:
num = 3 * (4 + 2)
In [4]:
num
Out[4]:
In [5]:
strng = "A string" " connected to another string"
In [6]:
strng
Out[6]:
In [7]:
lst = ["word", "two words", "short", "long"]
In [8]:
lst
Out[8]:
In [9]:
lst[2]
Out[9]:
In [10]:
lst[:-1]
Out[10]:
In [11]:
lst[1:]
Out[11]:
In [12]:
long_list = ["a", "c", "b", "d", "e", "dd", "f", "m", "p", "g"]
In [13]:
long_list
Out[13]:
In [14]:
long_list[4]
Out[14]:
In [15]:
long_list[3:7]
Out[15]:
Now we have something to work with.
In [16]:
history -n
In [17]:
_i2
Out[17]:
In [18]:
_i4
Out[18]:
In [19]:
history -l 6
In [20]:
history -l 7 -n
In [22]:
history -g strng
We can also use those previous commands.
In [23]:
%rerun 6
Out[23]:
In [24]:
%recall 5
In [25]:
strng = "A string" " connected to another string" " with more added this timw"
The %recall
command brings back the specified line from history and places it on the input line ready for you to edit before you run it. So in this case I added the third string.
In [26]:
strng
Out[26]:
The macro magic command allows us to take some lines form our history and turn them into a macro to re-execute them at any time.
In [27]:
%macro a_macro 7-11
In [28]:
a_macro
Out[28]:
In [29]:
print a_macro
For other uses of your history check out the edit and save magic commands. (Executing the lines below will pop up the help for each.)
In [30]:
edit?
In [31]:
save?
In [ ]: